/* 
 * File: timespandata.h
 * Project: QTimeTracker
 * Author: Steve Sindelar, http://stevesindelar.cz
 * Licence: NewBSD licence.
 */

#ifndef TIMESPANDATA_H
#define TIMESPANDATA_H

#include <QString>
#include <QStringList>

namespace Core
{

	/**
	 * Represents time span data. It is hours count, minutes count and seconds. 
	 * Hours count might be more than 24 that means no days or months.
	 */
	struct TimeSpanData
	{
		int hours;
		int minutes;
		int seconds;

		TimeSpanData() 
		{
			this->hours = this->minutes = this->seconds = 0;
		}

		inline TimeSpanData& operator+=(TimeSpanData& b)
		{
			this->seconds += b.seconds;
			this->minutes += this->seconds / 60;
			this->seconds %= 60;

			this->minutes += b.minutes;
			this->hours += this->minutes / 60;
			this->minutes %= 60;

			this->hours += b.hours;

			return *this;
		}

		inline bool operator <(const TimeSpanData& b) const
		{
			if (this->hours < b.hours) return true;
			else if (this->hours > b.hours) return false;
			else if (this->minutes < b.minutes) return true;
			else if (this->minutes > b.minutes) return false;
			return this->seconds < b.seconds;
		}

		inline static TimeSpanData fromSeconds(long secs)
		{
			TimeSpanData result;
			result.seconds = secs % 60;
			result.minutes = (secs / 60) % 60;
			result.hours = (secs / 60) / 60;
			return result;
		}

		inline QString toString() const
		{
			return  QString().sprintf("%02d:%02d:%02d", this->hours, this->minutes, this->seconds);
		}

		/**
		 * Converts string in format that is produced by toString method to TimeSpanData instance.
		 */ 
		inline static TimeSpanData fromString(const QString& str, bool& ok)
		{
			ok = true;
			TimeSpanData result;

			QStringList parts = str.split(":");
			if (parts.length() == 0) 
			{
				ok = false;
				return TimeSpanData();
			}

			result.hours = parts.at(0).toInt(&ok);
			if (!ok) return TimeSpanData();

			if (parts.length() >= 2)
			{
				result.minutes = parts.at(1).toInt(&ok);
				if (!ok) return TimeSpanData();
			}
			if (parts.length() >= 3)
			{
				result.seconds = parts.at(2).toInt(&ok);
				if (!ok) return TimeSpanData();
			}
	        
			return result;
		}

		/**
		 * Returns total number of seconds.
		 */
		inline long getSecs() const
		{
			return this->seconds + this->minutes*60 + this->hours*60*60;
		}
	};

}

#endif //TIMESPANDATA_H
